package GameEngine.Animation.Translation;

import java.util.ArrayList;

import GameEngine.helper.Log;
import GameEngine.helper.PAppletBridge;

public class Translation {

	private int Size;
	protected KeyFrame[] Frames;
	private ArrayList<KeyFrame> Keys = new ArrayList<KeyFrame>();

	private boolean locked = false;

	public Translation(int size) {
		Size = size;
		initFrames();
		locked = false;
	}

	private void initFrames() {
		Frames = new KeyFrame[Size];
		for (int i = 0; i < Frames.length; i++) {
			Frames[i] = null;
		}
	}

	public void add(KeyFrame kf) {
		if (!locked) {
			Keys.add(kf);
		} else {
			Log.warn("Translation already locked. Create new one.");
		}
	}

	private void toFramesArray() {
		KeyFrame[] a = Keys.toArray(new KeyFrame[Keys.size()]);
		for (KeyFrame kf : a) {
			int idx = kf.getFrameNumber();
			if ((idx >= 0) && (idx < Size)) {
				Frames[idx] = kf;
			} else {
				Log
						.warn("Dropping KeyFrames in Translation. OutOfBounds Keyframe Index.");
			}
		}
		locked = true;
	}

	public void interpolate() {
		toFramesArray();

		// suchen nach Indexpaar
		int from = 0;
		while (from < Frames.length) {
			while ((from < Frames.length) && (Frames[from] == null)) {
				from++;
			}
			int to = from + 1;
			while ((to < Frames.length) && (Frames[to] == null)) {
				to++;
			}

			// Interpolation
			if (to < Frames.length) {
				interpolate(from, to);
				System.out.println();
				System.out.println("interpolating between " + from + "-" + to);
				printFrames();
			}
			from = to;
		}
	}

	protected void interpolate(int from, int to) {
		KeyFrame KfFrom = Frames[from];
		KeyFrame KfTo = Frames[to];

		int diff = to - from;
		if (diff != 0) {
			for (int i = 0; i < diff; i++) {
				float amt = (i * 1.0f) / diff;
				Frames[from + i] = interpolate(from + i, KfFrom, KfTo, amt);
			}
		}
	}

	private KeyFrame interpolate(int fn, KeyFrame from, KeyFrame to, float amt) {
		int iposx = (int) PAppletBridge.lerp(from.getPosX(), to.getPosX(), amt);
		int iposy = (int) PAppletBridge.lerp(from.getPosY(), to.getPosY(), amt);
		float iangle = PAppletBridge.lerp(from.getAngle(), to.getAngle(), amt);
		int irotcenter = from.getImageMode();
		float ialpha = PAppletBridge.lerp(from.getAlpha(), to.getAlpha(), amt);
		float iscalex = PAppletBridge.lerp(from.getScaleX(), to.getScaleX(),
				amt);
		float iscaley = PAppletBridge.lerp(from.getScaleY(), to.getScaleY(),
				amt);

		return new KeyFrame(fn, iposx, iposy, iangle, irotcenter, ialpha,
				iscalex, iscaley);
	}

	public void printFrames() {
		System.out.println();
		for (int i = 0; i < Frames.length; i++) {
			KeyFrame kf = Frames[i];
			if (kf != null) {
				System.out.print(kf.getFrameNumber() + ":");
			} else {
				System.out.print("_:");
			}
		}
		System.out.println();
	}

}
